<?php
namespace app\api\controller\v1;
use app\api\model\AttendanceCurrLog;
use app\api\model\AttendanceGradeLog;
use app\api\model\AttendanceTeacherLog;
use app\api\model\DeviceAssociation;
use app\api\validate\NoticeValidate;
use app\api\validate\NewsValidate;
use app\api\validate\ActivitysValidate;
use app\api\validate\EleganceValidate;
use app\api\validate\StudentInfoValidate;
use app\api\validate\TemplateValidate;
use app\api\validate\CountdownValidate;
use app\api\validate\PowerValidate;
use app\api\validate\ScreenSaverValidate;
use app\api\validate\DevideConfigValidate;
use app\common\lib\Curl;
use think\Db;
use Qiniu\Auth;
use think\Log;

class Bancard extends Common{
	//获取通知公告
	public function getSchoolNotice(){

		$data = request()->param();
		$validate = new NoticeValidate;
		if (!$validate->scene('view')->check($data)) {
			return show(1, $validate->getError(), 0 , 200);
		}
		$limit = isset($data['limit'])?$data['limit']:10;
		//1.先得到设备code
		$device_code = isset($data['device_code'])?$data['device_code']:"";
        $list = db('notice')->alias('a')->leftJoin('__DEVICE_ASSOCIATION__ b', 'FIND_IN_SET(b.class_id,a.class_ids)')
            ->where('b.device_key', $device_code)
            ->field('a.id,a.title,a.image,a.description,a.content,a.created_at,a.start_time,a.istop,a.sort')
            ->order(['a.istop' => 'desc', 'a.sort' => 'asc', 'id' => 'desc'])
            ->paginate($limit)
            ->toArray();
		if(empty($list['data'])){
            return showTable(0, '获取成功',0, "", 200);
        }
        foreach ($list['data'] as $k=>$v){
		    $list['data'][$k]['content'] = $this->imageUrl($v['content']);
        }
        return showTable(0, '获取成功',$list['total'], $list['data'], 200);
	}
	//获取新闻动态
	public function getSchoolNews(){
	
		$data = request()->param();
		
		$validate = new NewsValidate;
		
		if (!$validate->scene('view')->check($data)) {
			return show(1, $validate->getError(), 0 , 200);
		}
		$limit = isset($data['limit'])?$data['limit']:10;
		//1.先得到设备code
		$device_code = isset($data['device_code'])?$data['device_code']:"";
        $list = db('news')->alias('a')->leftJoin('__DEVICE_ASSOCIATION__ b', 'FIND_IN_SET(b.class_id,a.class_ids)')->where('b.device_key', $device_code)->field('a.id,a.title,a.image,a.description,a.content,a.created_at,a.start_time')->paginate($limit)->toArray();
		if(empty($list['data'])){
            return showTable(0, '获取成功',0, "", 200);
        }
        foreach ($list['data'] as $k=>$v){
		    $list['data'][$k]['content'] = $this->imageUrl($v['content']);
        }
        return showTable(0, '获取成功',$list['total'], $list['data'], 200);
    }
    //获取教师风采
	public function getTeacherGraceful(){
	
		$data = request()->param();
		
		$validate = new NewsValidate;
		
		if (!$validate->scene('view')->check($data)) {
			return show(1, $validate->getError(), 0 , 200);
		}
		
        $limit = isset($data['limit'])?$data['limit']:10;
		//1.先得到设备code
		$device_code = isset($data['device_code'])?$data['device_code']:"";
        $list = db('teacher_graceful')->alias('a')->leftJoin('__DEVICE_ASSOCIATION__ b', 'FIND_IN_SET(b.class_id,a.class_ids)')->where('b.device_key', $device_code)->field('a.id,a.title,a.image,a.description,a.content,a.created_at,a.start_time')->paginate($limit)->toArray();
		if(empty($list['data'])){
            return showTable(0, '获取成功',0, "", 200);
        }
        foreach ($list['data'] as $k=>$v){
            $list['data'][$k]['content'] = $this->imageUrl($v['content']);
		    $list['data'][$k]['description'] = mb_substr($v['description'],0,100);
        }
        return showTable(0, '获取成功',$list['total'], $list['data'], 200);
	}
	//获取活动
	public function getSchoolActive(){
	
		$data = request()->param();
		
		$validate = new ActivitysValidate;
		
		if (!$validate->scene('view')->check($data)) {
			return show(1, $validate->getError(), 0 , 200);
		}
		
		$limit = isset($data['limit'])?$data['limit']:10;
		$offset = isset($data['offset'])?$data['offset']:1;
		$start = ($offset-1)*$limit;
		//1.先得到设备code
		//设备code
		$device_code = isset($data['device_code'])?$data['device_code']:"";
		//2.通过设备code找到班级id
		//基础平台提供接口通过code查询班级id
		$device_id = $this->getDeviceId($device_code);
		if(empty($device_id)){
			return showTable(1, '没有找到班级设备对应的id',0, "", 200);
		}
		$deviceA = db('device_association')->where(['device_id'=>$device_id])->field('class_id')->find();
		if(empty($deviceA)){
			return showTable(1, '没有找到对应的班级id',0, "", 200);
		}
		//3.通过班级id筛选出该班的所有公告
		$count =  db('activity')->where('FIND_IN_SET(:id,class_ids)',['id' => $deviceA['class_id']])->count();
		$result = db('activity')->where('FIND_IN_SET(:id,class_ids)',['id' => $deviceA['class_id']])->limit($start,$limit)->order('id desc,sort desc,created_at desc')->select();
		
		return showTable(0, '获取成功',$count, $result, 200);
	}
	//获取风采
	public function getSchoolElegance(){
	
		$data = request()->param();
		
		$validate = new EleganceValidate;
		
		if (!$validate->scene('view')->check($data)) {
			return show(0, $validate->getError(), 0 , 200);
		}
		
		$limit = isset($data['limit'])?$data['limit']:10;
		//1.先得到设备code
		$device_code = isset($data['device_code'])?$data['device_code']:"";
        $type = $data['type'];
		if($type == 1){
			$result = db('campus_elegance')
                      ->alias('a')
                      ->leftJoin('__DEVICE_ASSOCIATION__ b', 'FIND_IN_SET(b.class_id,a.class_ids)')
                      ->where(['a.type'=>$type])
                      ->where('b.device_key', $device_code)
                      ->field('a.id,a.title,a.description,a.image,a.images,a.istop')
                      ->order('a.istop desc,a.id desc')
                      ->paginate($limit)
                      ->toArray();
            foreach ($result['data'] as $key => $value) {
               if(!empty($value['images'])){
                   $result['data'][$key]['imagesPics'] = explode(',',$value['images']);
                   unset($result['data'][$key]['images']);
               }
            }
        }else{
            $result = db('campus_elegance')->alias('a')->leftJoin('__DEVICE_ASSOCIATION__ b', 'FIND_IN_SET(b.class_id,a.class_ids)')->where('video','not null')->where(['a.type'=>$type])->where('b.device_key', $device_code)->field('a.id,a.title,a.video')->paginate($limit)->toArray();
		}
		return showTable(0, '获取成功',$result['total'], $result['data'], 200);
	}
	//获取模板布局
	public function getFindClassPlateTemplate(){
		
		$data = request()->param();
		
		$validate = new TemplateValidate;
		
		if (!$validate->scene('view')->check($data)) {
			return show(1, $validate->getError(), 0 , 200);
		}
		$type 	= isset($data['type'])?$data['type']:1;
		//1.先得到设备code
		//设备code
		$device_code = isset($data['device_code'])?$data['device_code']:"";
		//2.通过设备code找到设备id
		//基础平台提供接口通过code查询设备id

		$device_id = $this->getDeviceId($device_code);
		if(empty($device_id)){
			return showTable(1, '没有找到班级设备对应的id',0, "", 200);
		}
		$template_id = db('device_template_type')->where(['type'=>$type])->where(['d_ass_id'=>$device_id])->field('template_id')->find();
		if(empty($template_id)){
			return showTable(1, '没有找到对应的模板id',0, "", 200);
		}
		//3.通过班级id筛选出该班的所有模板
		$result = db('class_plate_template')->where(['type'=>$type,'id'=>$template_id])->order('id desc,sort desc')->field('id,template_code,school_id,type')->find();
		if(empty($result)){
			return showTable(1, '暂无布局模板',0, $result, 200);
		}
		$result['template_code'] = json_decode($result['template_code']);
		$result['device_id'] = $device_id;
		return showTable(0, '获取成功',1, $result, 200);
	}
	//获取倒计时
	public function getSetupCountdown(){
		$data = request()->param();
		$validate = new CountdownValidate;
		if (!$validate->scene('view')->check($data)) {
			return show(1, $validate->getError(), 0 , 200);
		}
		//1.先得到设备code
		//设备code
		$device_code = isset($data['device_code'])?$data['device_code']:"";
		//2.通过设备code找到设备id
		//基础平台提供接口通过code查询班级id
		$device_id = $this->getDeviceId($device_code);
		if(empty($device_id)){
			return showTable(1, '没有找到班级设备对应的id',0, "", 200);
		}
        $countdown = db('device_association')->where(['device_id'=>$device_id])->find();
		if(empty($countdown)){
			return showTable(1, '没有找到对应的倒计时',0, "", 200);
		}
		//3.通过班级id筛选出该班的所有公告
		$result = db('setup_countdown')->where(['id'=>$countdown['countdown_id']])->find();

		if(empty($result)){
			return showTable(1, '暂无倒计时设置',0, $result, 200);
		}
        $result['class_id'] = $countdown['class_id'];
		return showTable(0, '获取成功',1, $result, 200);
	}
	//获取开关机
	public function getSettingSwitch(){
		$data = request()->param();
		
		$validate = new PowerValidate;
		
		if (!$validate->scene('view')->check($data)) {
			return show(1, $validate->getError(), 0 , 200);
		}
		//1.先得到设备code
		//设备code
		$device_code = isset($data['device_code'])?$data['device_code']:"";
		//2.通过设备code找到设备id
		//基础平台提供接口通过code查询班级id
		$device_id = $this->getDeviceId($device_code);
		if(empty($device_id)){
			return showTable(1, '没有找到班级设备对应的id',0, "", 200);
		}
		$switch = db('device_association')->where(['device_id'=>$device_id])->field('switch_id,updated_at_switch')->find();

		if(empty($switch)){
			return showTable(1, '没有找到对应的开关机设置id',0, "", 200);
		}
		//3.通过班级id筛选出该班的所有公告
		$result = db('setting_switch')->where(['id'=>$switch['switch_id']])->field('id,switching_data,start_time,end_time')->find();
		
		if(empty($result)){
			return showTable(1, '暂无倒计时设置',0, $result, 200);
		}
		//周期转化为数组
		$w = [1,2,3,4,5,6,0];
		$week = explode(',',$result['switching_data']);
		foreach ($w as $key => $value) {
		    $s1 = 0;
		    foreach ($week as $k => $v) {
		        if($value == $v){
		            $s1 = 1;
		        }
		    }
		    $result['week'][] = $s1;
		}
		//开始时间转化
		$n = explode(':',$result['start_time']);
		$result['on']['h'] = (int)$n[0];
		$result['on']['m'] = (int)$n[1];
		//结束时间转化
		$f = explode(':',$result['end_time']);
		$result['off']['h'] = (int)$f[0];
		$result['off']['m'] = (int)$f[1];
        $result['updated_at'] = date($switch['updated_at_switch']);
		unset($result['switching_data']);
		unset($result['start_time']);
		unset($result['end_time']);
		return showTable(0, '获取成功',1, $result, 200);
	}
	//获取屏保
	public function getScreenSaver(){
		$data = request()->param();
		
		$validate = new ScreenSaverValidate;
		
		if (!$validate->scene('view')->check($data)) {
			return show(1, $validate->getError(), 0 , 200);
		}
		//1.先得到设备code
		//设备code
		$device_code = isset($data['device_code'])?$data['device_code']:"";
		//2.通过设备code找到设备id
		//基础平台提供接口通过code查询班级id
		$device_id = $this->getDeviceId($device_code);
		if(empty($device_id)){
			return showTable(1, '没有找到班级设备对应的id',0, "", 200);
		}
		$screen_saver = db('device_association')->where(['device_id'=>$device_id])->field('screen_saver_id,updated_at_screen')->find();
        $screen_saver_id = isset($screen_saver['screen_saver_id'])?$screen_saver['screen_saver_id']:'';
		if(empty($screen_saver_id)){
			return showTable(1, '没有找到对应的屏保设置id',0, "", 200);
		}
		//3.通过班级id筛选出该班的所有公告
		$result = db('screen_saver')->where(['id'=>$screen_saver_id])->field('id,switching_data,title,off_time,content,images,start_time,end_time,type,user_id,start_date,end_date')->find();
		
		if(empty($result)){
			return showTable(1, '暂无对应的屏保设置',0, $result, 200);
		}
		//处理图片为数组
		if($result['images']){
			$result['images'] = explode(',',$result['images']);
		}
		//周期转化为数组
		$w = [1,2,3,4,5,6,0];
		$week = explode(',',$result['switching_data']);
		foreach ($w as $key => $value) {
		    $s1 = 0;
		    foreach ($week as $k => $v) {
		        if($value == $v){
		            $s1 = 1;
		        }
		    }
		    $result['week'][] = $s1;
		}
		//开始时间转化
		$n = explode(':',$result['start_time']);
		$result['on']['h'] = (int)$n[0];
		$result['on']['m'] = (int)$n[1];
		//结束时间转化
		$f = explode(':',$result['end_time']);
		$result['off']['h'] = (int)$f[0];
		$result['off']['m'] = (int)$f[1];
		//
		$result['start_date'] = date( "Y-m-d",$result['start_date']);
		$result['end_date'] = date( "Y-m-d",$result['end_date']);

        $result['updated_at'] = date($screen_saver['updated_at_screen']);
		unset($result['switching_data']);
		unset($result['start_time']);
		unset($result['end_time']);

		return showTable(0, '获取成功',1, $result, 200);
	}
	//获取配置项
	public function getDevideConfig(){
		$data = request()->param();
		
		$validate = new DevideConfigValidate;
		
		if (!$validate->scene('view')->check($data)) {
			return show(1, $validate->getError(), 0 , 200);
		}
		//1.先得到设备code
		//设备code
		$device_code = isset($data['device_code'])?$data['device_code']:"";
		//2.通过设备code找到设备id
		//基础平台提供接口通过code查询班级id
		$device_id = $this->getDeviceId($device_code);

		if(empty($device_id)){
			return showTable(1, '没有找到班级设备对应的id',0, "", 200);
		}
		$info_id = db('device_association')->where(['device_id'=>$device_id])->field('id,switch_id,screen_saver_id,exam_id,class_id,updated_at_face,updated_at_countdown,updated_at_screen,updated_at_switch')->find();
		if(empty($info_id)){
			return showTable(1, '没有找到对应设置id',0, "", 200);
		}

        $switch = null;
		if($info_id['switch_id']){
			$switch = db('setting_switch')->where(['id'=>$info_id['switch_id']])->field('id,switching_data,start_time,end_time,updated_at')->find();

			if(!empty($switch)){
                //周期转化为数组
                $w = [1,2,3,4,5,6,0];
                $week = explode(',',$switch['switching_data']);
                foreach ($w as $key => $value) {
                    $s1 = 0;
                    foreach ($week as $k => $v) {
                        if($value == $v){
                            $s1 = 1;
                        }
                    }
                    $switch['week'][] = $s1;
                }
                //开始时间转化
                $n = explode(':',$switch['start_time']);
                $switch['on']['h'] = (int)$n[0];
                $switch['on']['m'] = (int)$n[1];
                //结束时间转化
                $f = explode(':',$switch['end_time']);
                $switch['off']['h'] = (int)$f[0];
                $switch['off']['m'] = (int)$f[1];
                $switch['updated_at'] = $info_id['updated_at_switch'];
                unset($switch['switching_data']);
                unset($switch['start_time']);
                unset($switch ['end_time']);
			}

		}
        $screen_saver = null;
		if($info_id['screen_saver_id']){
			//3.通过班级id筛选出该班的屏保
			$screen_saver = db('screen_saver')->where(['id'=>$info_id['screen_saver_id']])->field('id,switching_data,title,off_time,content,images,start_time,end_time,type,user_id,start_date,end_date,updated_at')->find();

			if(!empty($screen_saver)){
                //处理图片为数组
                if($screen_saver['images']){
                    $screen_saver['images'] = explode(',',$screen_saver['images']);
                }

                //周期转化为数组
                $w = [1,2,3,4,5,6,0];
                $week = explode(',',$screen_saver['switching_data']);
                foreach ($w as $key => $value) {
                    $s1 = 0;
                    foreach ($week as $k => $v) {
                        if($value == $v){
                            $s1 = 1;
                        }
                    }
                    $screen_saver['week'][] = $s1;
                }

                if($screen_saver['start_time']){
                    //开始时间转化
                    $n = explode(':',$screen_saver['start_time']);
                    $screen_saver['on']['h'] = (int)$n[0];
                    $screen_saver['on']['m'] = (int)$n[1];
                }
                if($screen_saver['end_time']){
                    //结束时间转化
                    $f = explode(':',$screen_saver['end_time']);
                    $screen_saver['off']['h'] = (int)$f[0];
                    $screen_saver['off']['m'] = (int)$f[1];
                }


                //
                $screen_saver['start_date'] = date( "Y-m-d",$screen_saver['start_date']);
                $screen_saver['end_date'] = date( "Y-m-d",$screen_saver['end_date']);
                $screen_saver['updated_at'] = $info_id['updated_at_screen'];

                unset($screen_saver['switching_data']);
                unset($screen_saver['start_time']);
                unset($screen_saver['end_time']);
			}



		}

        $exam_mode = db('examination_mode')
            ->alias('a')
            ->leftJoin('examination_room b','a.id=b.mode_id')
            ->where(['b.class_id'=>$info_id['class_id']])
            ->order('b.update_time', 'desc')
            ->field('a.exam_name,a.start_time,a.end_time,a.update_time as updated_at,b.id')
            ->find();

        if($exam_mode){
            $exam_suject = db('examination_subject')->where(['r_id'=>$exam_mode['id']])->select();
            $exam_mode['updated_at'] = strtotime(date($exam_mode['updated_at']));
            $exam_mode['subjects'] = $exam_suject;
        }
        $version = $this->app_version();
		$result['screen_saver'] = $screen_saver;
		$result['switch'] = $switch;
		$result['exam'] = empty($exam_mode)?null:$exam_mode;
		$result['version'] = $version;
        $result['faces']['updated_at'] = $info_id['updated_at_face'];
		return showTable(0, '获取成功',1, $result, 200);
	}
	//首页家长留言
	public function getParentsLeaveMessages(){
		$data = request()->param();
	}
	//某个学生的留言
	public function getMessages(){
		$data = request()->param();
	}
	//获取设备激活信息
	public function getDeviceCode(){
        $data = request()->param();
        $validate = new DevideConfigValidate();
        if (!$validate->scene('deviceCode')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        $result = $this->get_device_code($data);

        if(!empty($result)){
              return showTable(0, '获取成功',1, $result[0], 200);
        }else{
            return showTable(1, '设备没有激活',0, "", 200);
        }
    }
    //设备激活认证
    public function deviceActive(){
        $data = request()->param();
        $validate = new DevideConfigValidate();
        if (!$validate->scene('deviceActive')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }

        $result=$this->device_active($data);
        if($result['code'] == 1){
            return showTable(0, $result['msg'],1, $result['data'], 200);
        }else{
            return showTable(1, $result['msg'],1, "", 200);
        }

    }
    //获取七牛token
    public function getQiniuToken(){
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey =config('app.qiniu.accesskey');
        $secretKey = config('app.qiniu.secretkey');
        $bucket = config('app.qiniu.bucket');
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        return showTable(0, '获取成功',1, $token, 200);
    }
    //通过卡号获取学生信息
    public function getStudentInfoForCode(){
        $data = request()->param();
        $validate = new StudentInfoValidate();
        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        $result=$this->card_info($data);
        return showTable(0, '设置成功',1, $result, 200);
    }
    //获取班级信息
    public function getClassInfo(){
        $data = request()->param();

        $validate = new DevideConfigValidate;

        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        //设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id
        //基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到班级设备对应的id',0, "", 200);
        }
        $info_id = db('device_association')->where(['device_id'=>$device_id])->field('class_id')->find();
        if(empty($info_id)){
            return showTable(1, '没有找到对应设置id',0, "", 200);
        }
        $result=$this->class_info_id($info_id['class_id']);
        if(!empty($result)){
            return showTable(0, "获取成功",1, $result, 200);
        }else{
            return showTable(1, "获取失败",1, "", 200);
        }
    }
    //获取人脸信息
    public function getFaces(){
        $data = request()->param();

        $validate = new DevideConfigValidate;

        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        //设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id
        //基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到班级设备对应的id',0, "", 200);
        }
        $info_id = db('device_association')->where(['device_id'=>$device_id])->field('id,switch_id,screen_saver_id,exam_id,class_id,updated_at_face')->find();
        if(empty($info_id)){
            return showTable(1, '没有找到对应设置id',0, "", 200);
        }
        $faces = $this->student_faces($info_id['class_id']);
        $faces['updated_at'] =$info_id['updated_at_face'];
        unset($faces['updated_at_face']);
        return showTable(0, '获取成功',1, $faces, 200);
    }
    //前端拉取数据设置更新时间
    public function updateFaces(){
        $data = request()->param();
        $validate = new DevideConfigValidate;
        if (!$validate->scene('updated')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        //设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id
        //基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到班级设备对应的设备id',0, "", 200);
        }
        $info_id = db('device_association')->where(['device_id'=>$device_id])->update([
            'updated_at_face'=>$data['updated_at']
        ]);
        if($info_id){
            return showTable(0, '更新成功',1, $info_id, 200);
        }else{
            return showTable(1, '更新失败稍后重试',1, "", 200);
        }

    }
    //获取考试
    public function getExam(){
        $data = request()->param();

        $validate = new DevideConfigValidate;

        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        //设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id
        //基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到班级设备对应的id',0, "", 200);
        }
        $info_id = db('device_association')->where(['device_id'=>$device_id])->field('id,switch_id,screen_saver_id,exam_id,class_id')->find();
        if(empty($info_id)){
            return showTable(1, '没有找到对应设置id',0, "", 200);
        }
        $exam_mode = db('examination_mode')
            ->alias('a')
            ->leftJoin('examination_room b','a.id=b.mode_id')
            ->where(['b.class_id'=>$info_id['class_id']])
            ->order('b.update_time', 'desc')
            ->field('a.exam_name,a.start_time,a.end_time,a.update_time as updated_at,b.id')
            ->find();

        if($exam_mode){
            $exam_suject = db('examination_subject')->where(['r_id'=>$exam_mode['id']])->select();
            $exam_mode['updated_at'] = strtotime(date($exam_mode['updated_at']));
            $exam_mode['subjects'] = $exam_suject;
        }
        $result = empty($exam_mode['updated_at'])?null:$exam_mode;
        return showTable(0, '获取成功',1, $result, 200);
    }
    //值日表
    public function getDuty(){
        $data = request()->param();

        $validate = new DevideConfigValidate;

        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        //设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id
        //基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到班级设备对应的id',0, "", 200);
        }
        $info_id = db('device_association')->where(['device_id'=>$device_id])->field('id,switch_id,screen_saver_id,exam_id,class_id')->find();
        if(empty($info_id)){
            return showTable(1, '没有找到对应设置id',0, "", 200);
        }
        $duty = [];
        $count = 0;
        $weekarray=array("0","1","2","3","4","5","6"); //先定义一个数组
        $curWeek = $weekarray[date("w")];

        if(isset($info_id['class_id'])){
            $count = db('duty')->where('week',$curWeek)->where(['class_id'=>$info_id['class_id']])->count();
            $duty = db('duty')->where('week',$curWeek)->where(['class_id'=>$info_id['class_id']])->select();
        }

        $student_id = array_filter(array_column($duty,'student_id'));
        $students = $this->get_student_info($student_id);
        foreach ($duty as $k=>$v){
            if(isset($students[$v['student_id']])){
                $duty[$k]['name'] = $students[$v['student_id']]['name'];
                $duty[$k]['avatar'] = $students[$v['student_id']]['avatar'];
            }
        }
        return showTable(0, '获取成功',$count, $duty, 200);

    }
    //根据设备key获取设备id
    public function getKeyDeviceId(){
        $data = request()->param();

        $validate = new DevideConfigValidate;

        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        //设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id
        //基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到班级设备对应的id',0, "", 200);
        }
        return showTable(0, '获取成功',1, $device_id, 200);
    }
    //获取班级课表
    public function getClassTimeable(){
        $data = request()->param();

        $validate = new DevideConfigValidate;

        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        //设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id
        //基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到班级设备对应的id',0, "", 200);
        }

        $info_id = db('device_association')->where(['device_id'=>$device_id])->field('id,switch_id,screen_saver_id,exam_id,class_id')->find();
        if(empty($info_id)){
            return showTable(1, '没有找到对应设置id',0, "", 200);
        }
	    $info = $this->get_timetable($info_id['class_id']);
        return showTable(0, '获取成功',10, $info, 200);
    }
    //获取今日课程表
    public function getTodayTimetable(){
        $data = request()->param();

        $validate = new DevideConfigValidate;

        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        //设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        if(empty($device_code)){
            return showTable(1, '没有找到班级设备对应的id',0, "", 200);
        }
        $info_id = db('device_association')->where(['device_key'=>$device_code])->field('class_id')->find();
        if(empty($info_id)){
            return showTable(1, '没有找到对应设置id',0, "", 200);
        }
        $info = $this->get_today_timetable($info_id['class_id']);
        return showTable(0, '获取成功',10, $info, 200);

    }
    //获取班级光荣榜
    public function getHoner(){
        $data = request()->param();

        $validate = new DevideConfigValidate;

        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        //设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id
        //基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到班级设备对应的id',0, "", 200);
        }
        $info_id = db('device_association')->where(['device_id'=>$device_id])->field('id,switch_id,screen_saver_id,exam_id,class_id')->find();
        if(empty($info_id)){
            return showTable(1, '没有找到对应设置id',0, "", 200);
        }
        $info = $this->get_honer($info_id['class_id']);
        return showTable(0, '获取成功',10, $info, 200);
    }
    //获取优秀班集体
    public function getExcellent(){
        $data = request()->param();

        $validate = new DevideConfigValidate;

        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        //设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id
        //基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到设备对应的班级id',0, "", 200);
        }
        $info_id = db('device_association')->where(['device_id'=>$device_id])->field('id,switch_id,screen_saver_id,exam_id,class_id')->find();

        if(empty($info_id)){
            return showTable(1, '没有找到对应设置id',0, "", 200);
        }
        $count =  db('excellent_class')->where('FIND_IN_SET(:id,class_ids)',['id' => $info_id['class_id']])->where(['show'=>1])->limit(0,5)->count();
        $result = db('excellent_class')->where('FIND_IN_SET(:id,class_ids)',['id' => $info_id['class_id']])->where(['show'=>1])->limit(0,5)->order('istop desc,sort desc')->select();
        return showTable(0, '获取成功',$count, $result, 200);
    }
    //获取老师课程表
    public function getTeacherTimetable(){

    }
    //获取老师考勤是否考勤 列表
    public function getTeacherAttendance(){
        $data = request()->param();
        $validate = new DevideConfigValidate;
        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id 基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到班级设备对应的id',0, "", 200);
        }
        $info = db('device_association')->where(['device_id'=>$device_id])->field('class_id')->find();
        $school_info = $this->codeToTeacherLists($info['class_id']);
        if(empty($school_info)){
            return showTable(1, '该学校没有老师',0, "", 200);
        }
        //4.查询出当前时间里是否有考勤事件
        $attendanceEvent =  db('attendance_settings')
                            ->where('start_time','<=',date('H:i:s',time()))
                            ->where('end_time','>=',date('H:i:s',time()))
                            ->where(['type'=>1])
                            ->find();
        if(empty($attendanceEvent)){
            return showTable(1, '暂无考勤事件',0, "", 200);
        }
        //p($attendanceEvent);
        //5.获取考勤事件记录里的所有老师
        $today_start = strtotime(date("Y-m-d"),time());
        $today_end = $today_start+60*60*24;
        $attendanceTeacher = db('attendance_teacher_log')
                            ->where(['event_id'=>$attendanceEvent['id']])
                            ->where(['school_id'=>$school_info[0]['school_id']])
                            ->whereTime('att_time', 'between', [$today_start, $today_end])
                            ->column('status','teacher_id');
        //6.组合出新的老师是否考勤的列表
        $lists = [
            'punch'=>[],
            'nopunch'=>[]
        ];
        foreach ($school_info as $k=>$v){
            if(isset($attendanceTeacher[$v['id']])){
                $lists['punch'][] = $school_info[$k];
            }else{
                $lists['nopunch'][] = $school_info[$k];
            }
        }
        $lists['event'] = $attendanceEvent;
        //p($lists);die;
        return showTable(0, '获取成功',0, $lists, 200);
    }
    //上传老师考勤结果进行记录
    public function pustTeacherAttendance(){
        $data = request()->param();
        $validate = new DevideConfigValidate;
        if (!$validate->scene('attendance')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //获取考勤事件
        $attendanceEvent =  db('attendance_settings')
                            ->where(['id'=>$data['event_id']])
                            ->find();

        if(empty($attendanceEvent)){
            return showTable(1, '考勤事件已不存在',0, "", 200);
        }
        //当前时间
        $curTime = date('H:i:s',time());
        //考勤结束时间
        $attr_end_time = strtotime($attendanceEvent['end_time']);
        //考勤结束时间+延迟时间
        $end_time = date("H:i:s", strtotime($attr_end_time ." +".$attendanceEvent['att_range'] ."min"));
        //如果当前时间小于考勤结束时间+延迟时间时认为还在考勤范围
        if($curTime < $attr_end_time){
            //当前时间小于考勤结束时间时为正常
            $data['status'] = 1;
        }else if($curTime > $attr_end_time && $curTime < $end_time ){
            //当前时间小于结束时间并且小于勤结束时间+延迟时间时认为还在考勤范围，但是是迟到
            $data['status'] = 2;
        }else{
            //否则算不在考勤范围
            return showTable(1, '不在考勤时间范围',0, "", 200);
        }
        $curDate =  date('Y-m-d',time());
        //判断该时间段是否有该老师的考勤
        $res = AttendanceTeacherLog::where(['teacher_id'=>$data['teacher_id'],'event_id'=>$data['event_id']])
            ->whereTime('att_time', 'between', [$curDate.' 00:00:00', $curDate.' 23:59:59'])
            ->find();
        if($res){
            return showTable(1, '已考勤',0, "", 200);
        }
        //添加记录
	    $result = AttendanceTeacherLog::create([
            'event_id' => $data['event_id'],
            'att_time' => time(),
            'school_id' => $data['school_id'],
            'teacher_id' => $data['teacher_id'],
            'status' => $data['status']
        ]);
        return showTable(0, '考勤成功',0, '', 200);
    }
    //获取班牌学生考勤列表
    public function getClassAttendance(){
        $data = request()->param();
        $validate = new DevideConfigValidate;
        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id 基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到班级设备对应的id',0, "", 200);
        }
        $info = db('device_association')->where(['device_id'=>$device_id])->field('class_id')->find();
        $student_info = $this->students_list($info['class_id']);
        if(empty($student_info)){
            return showTable(1, '该班没有学生',0, "", 200);
        }
        //4.查询出当前时间里是否有考勤事件
        $attendanceEvent =  db('attendance_settings')
            ->where('start_time','<=',date('H:i:s',time()))
            ->where('end_time','>=',date('H:i:s',time()))
            ->where(['grade_id'=>$student_info[0]['grade_id']])
            ->where(['type'=>2])
            ->find();
        if(empty($attendanceEvent)){
            return showTable(1, '暂无考勤事件',0, "", 200);
        }
        //5.获取考勤事件记录里的所有学生
        $today_start = strtotime(date("Y-m-d"),time());
        $today_end = $today_start+60*60*24;
        $attendanceStudent = db('attendance_grade_log')
            ->where(['event_id'=>$attendanceEvent['id']])
            ->where(['class_id'=>$info['class_id']])
            ->whereTime('att_time', 'between', [$today_start, $today_end])
            ->column('grade_id','student_id');
        //6.组合出新的老师是否考勤的列表
        $lists = [
            'punch'=>[],
            'nopunch'=>[]
        ];
        foreach ($student_info as $k=>$v){
            if(isset($attendanceStudent[$v['id']])){
                $lists['punch'][] = $student_info[$k];
            }else{
                $lists['nopunch'][] = $student_info[$k];
            }
        }
        $lists['event'] = $attendanceEvent;
        //p($lists);die;
        return showTable(0, '获取成功',0, $lists, 200);
    }
    //上传学生考勤结果进行记录
    public function pustClassAttendance(){
        $data = request()->param();
        $validate = new DevideConfigValidate;
        if (!$validate->scene('stu_attendance')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //获取考勤事件
        $attendanceEvent =  db('attendance_settings')
            ->where(['id'=>$data['event_id']])
            ->find();

        if(empty($attendanceEvent)){
            return showTable(1, '考勤事件已不存在',0, "", 200);
        }
        //当前时间
        $curTime = date('H:i:s',time());
        //考勤结束时间
        $attr_end_time = strtotime($attendanceEvent['end_time']);
        //考勤结束时间+延迟时间
        $end_time = date("H:i:s", strtotime($attr_end_time ." +".$attendanceEvent['att_range'] ."min"));
        //如果当前时间小于考勤结束时间+延迟时间时认为还在考勤范围
        if($curTime < $attr_end_time){
            //当前时间小于考勤结束时间时为正常
            $data['status'] = 1;
        }else if($curTime > $attr_end_time && $curTime < $end_time ){
            //当前时间小于结束时间并且小于勤结束时间+延迟时间时认为还在考勤范围，但是是迟到
            $data['status'] = 2;
        }else{
            //否则算不在考勤范围
            return showTable(1, '不在考勤时间范围',0, "", 200);
        }
        $curDate =  date('Y-m-d',time());
        //判断该时间段是否有该学生的考勤
        $res = AttendanceGradeLog::where(['student_id'=>$data['student_id'],'event_id'=>$data['event_id']])
            ->whereTime('att_time', 'between', [$curDate.' 00:00:00', $curDate.' 23:59:59'])
            ->find();
        if($res){
            return showTable(1, '已考勤',0, "", 200);
        }
        $info = $this->class_info_id($data['class_id']);
        //添加记录
        $result = AttendanceGradeLog::create([
            'event_id' => $data['event_id'],
            'att_time' => time(),
            'school_id' => $info['school_id'],
            'student_id' => $data['student_id'],
            'class_id' => $data['class_id'],
            'grade_id' => $info['grade_id'],
            'status' => $data['status']
        ]);
        return showTable(0, '考勤成功',0, $result, 200);
    }

    //获取课程考勤列表
    public function getCurriculumAttendance(){
        $data = request()->param();
        $validate = new DevideConfigValidate;
        if (!$validate->scene('view')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id 基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到设备对应的id',0, "", 200);
        }
        $info = db('device_association')->where(['device_id'=>$device_id])->field('class_id')->find();
        if(empty($info)){
            return showTable(1, '没有找到班级对应的设备',0, "", 200);
        }
        //3.检测该班级下的课程在当前时间需要考勤不is_clock:0没有，1有
        $attendanceEvent = $this->is_check_attendace($info['class_id']);
        
        if($attendanceEvent['code'] == 0){
           return showTable(1, $attendanceEvent['msg'],0, "", 200); 
        }
        $student_info = $this->students_list($info['class_id']);
       
        if(empty($student_info)){
            return showTable(1, '该班没有学生',0, "", 200);
        }
        //5.获取考勤事件记录里的所有学生
        $today_start = date("Y-m-d H:i:s",strtotime($attendanceEvent['data']['start_time']));
        $today_end = date("Y-m-d H:i:s",strtotime($attendanceEvent['data']['end_time']." +".$attendanceEvent['data']['att_range'] ."min"));
        $attendanceStudent = db('attendance_curr_log')
            ->where(['event_id'=>$attendanceEvent['data']['id']])
            ->where(['class_id'=>$info['class_id']])
            ->whereTime('att_time', 'between', [$today_start, $today_end])
            ->column('subject_id','student_id');
        //6.组合出新的老师是否考勤的列表
        $lists = [
            'punch'=>[],
            'nopunch'=>[]
        ];
        foreach ($student_info as $k=>$v){
            if(isset($attendanceStudent[$v['id']])){
                $lists['punch'][] = $student_info[$k];
            }else{
                $lists['nopunch'][] = $student_info[$k];
            }
        }
        $lists['event'] = $attendanceEvent['data'];
        return showTable(0, '获取成功',0, $lists, 200);
    }
    //上传课程考勤结果进行记录
    public function pustCurriculumAttendance(){
        $data = request()->param();
        $validate = new DevideConfigValidate;
        if (!$validate->scene('curr_attendance')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //通过事件id获取该事件的信息
        $allInfo = $this->get_curriculum_info($data['event_id'],$data['student_id']);
        if(empty($allInfo)){
            return showTable(1, '当前时间暂无课程考勤事件',0, "", 200);
        }
        
        
        $curDate =  date('Y-m-d',time());
        $curTime =  date('Y-m-d H:i:s',time());
        //判断该时间段是否有该老师的考勤
        $today_start = strtotime($curDate.$allInfo['start_time']);
        $today_end = strtotime($curDate.$allInfo['start_time'])+60*$allInfo['clock_in_time'];
        
        if($curTime<$today_start){
            $att_status = 1;
        }else if($curTime<$today_end){
            $att_status = 2;
        }else{
            return showTable(1, '超出考勤时间',0, "", 200);
        }

        $res = AttendanceCurrLog::where(['student_id'=>$data['student_id'],'event_id'=>$data['event_id']])
                ->whereTime('att_time', '>', $today_end)
                ->find();
        if($res){
            return showTable(1, '已考勤',0, "", 200);
        }
        

        $ndata = [
            'event_id'=>$allInfo['id'],
            'event_name'=>"课程考勤",
            'school_id'=>$allInfo['school_id'],
            'class_id'=>$allInfo['class_id'],
            'section_num'=>$allInfo['number'],
            'class_name'=>$allInfo['class_name'],
            'classroom_id'=>$allInfo['classroom_id'],
            'classroom_name'=>$allInfo['classroom_name'],
            'building_id'=>$allInfo['building_id'],
            'building_name'=>$allInfo['building_name'],
            'subject_id'=>$allInfo['subject_id'],
            'subject_name'=>$allInfo['subject_name'],
            'teacher_id'=>$allInfo['teacher_id'],
            'teacher_name'=>$allInfo['teacher_name'],
            'att_status'=> $att_status,
            'cou_start_time'=>$allInfo['start_time'],
            'cou_end_time'=>$allInfo['end_time'],
            'student_id'=>$allInfo['student']['id'],
            'student_name'=>$allInfo['student']['name'],
            'student_number'=>$allInfo['student']['number'],
            'grade_name'=>$allInfo['student']['grade_name'],
            'grade_id'=>$allInfo['student']['grade_id'],
            'att_time'=>time(),
            'created_at'=>date('Y-m-d H:i:s', time()),
        ];
        Db::startTrans();
        try {
            AttendanceCurrLog::create($ndata);
            Db::commit();
        } catch (Exception $e) {
            $msg = $e->getMessage();
            Db::rollback();
            return showTable(1, $msg,0, "", 200);
        }
        return showTable(0, '考勤成功',0, "", 200);
    }

    //通过刷卡获取老师信息
    public function cardToTeacherInfo(){

        $data = request()->param();
        $validate = new DevideConfigValidate;
        if (!$validate->scene('card_teacher')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id 基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到设备对应的id',0, "", 200);
        }
        $info = db('device_association')->where(['device_id'=>$device_id])->field('class_id')->find();
        if(empty($info)){
            return showTable(1, '没有找到班级对应的设备',0, "", 200);
        }
        $info = $this->get_by_card_teacher($data['card_number'],$info['class_id']);
        if(empty($info)){
            return showTable(1, '老师不存在',0, "", 200);
        }
        return showTable(0, '获取成功',0, $info, 200);
    }
    public function cardToInfo(){
        $data = request()->param();
        $validate = new DevideConfigValidate;
        if (!$validate->scene('card_teacher')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id 基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到设备对应的id',0, "", 200);
        }
        $info = db('device_association')->where(['device_id'=>$device_id])->field('class_id')->find();
        if(empty($info)){
            return showTable(1, '没有找到班级对应的设备',0, "", 200);
        }
        $info = $this->get_by_card_info($data['card_number'],$info['class_id']);
        if(empty($info)){
            return showTable(1, '老师不存在',0, "", 200);
        }
        return showTable(0, '获取成功',0, $info, 200);
    }
    //通过刷卡获取学生信息
    public function cardToStudentInfo(){

        $data = request()->param();
        $validate = new DevideConfigValidate;
        if (!$validate->scene('card_student')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        //1.先得到设备code
        $device_code = isset($data['device_code'])?$data['device_code']:"";
        //2.通过设备code找到设备id 基础平台提供接口通过code查询班级id
        $device_id = $this->getDeviceId($device_code);
        if(empty($device_id)){
            return showTable(1, '没有找到设备对应的id',0, "", 200);
        }
        $info = db('device_association')->where(['device_id'=>$device_id])->field('class_id')->find();
        if(empty($info)){
            return showTable(1, '没有找到班级对应的设备',0, "", 200);
        }

        $info = $this->get_by_card_student($data['card_number'],$info['class_id']);
        if(empty($info)){
            return showTable(1, '学生不存在',0, "", 200);
        }
        return showTable(0, '获取成功',0, $info, 200);
    }
    //基础数据通知电子班牌前端刷新
    public function baseSocketPush(){
        $data = request()->param();

        $validate = new DevideConfigValidate;
        if (!$validate->scene('socket')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
        $this->socket_push($data['class_id'],$data['content']);
    }

    public function weacher(){
        $data = request()->param();
        $validate = new DevideConfigValidate;
        if (!$validate->scene('weacher')->check($data)) {
            return show(1, $validate->getError(), 0 , 200);
        }
		$data = [
			"source" => 'pc',
			"weather_type"=> 'air|observe|tips|forecast_24h',
			"province"=> $data['province'],
			"city"=> $data['city']
		];
		$c = (new Curl())->post("https://wis.qq.com/weather/common",$data);
		$d = json_decode($c,true);
		return showTable(0, '获取成功',0, $d['data'], 200);
    }
}

